#include "widget.h"
#include "ui_widget.h"
#include <QUrl>
#include <QNetworkRequest>
#include <QJsonDocument>
#include <QJsonArray>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    client = new QNetworkAccessManager(this);
    connect(client, &QNetworkAccessManager::finished,
            this, &Widget::handle_reply);
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_pushButton_clicked()
{
    QUrl url("https://v2.jinrishici.com/sentence");
    QNetworkRequest request(url);
    request.setRawHeader("X-User-Token", "EsJHJ/1f3WJWXJo3d7qxs3sV7GW5GZN4");
    client->get(request);
}

void Widget::handle_reply(QNetworkReply* reply)
{
    QJsonDocument json = QJsonDocument::fromJson(reply->readAll());
    qDebug() << json.toJson();

    QString content = json["data"]["origin"]["title"].toString();
    content.append("\n\n");
    content.append(json["data"]["origin"]["dynasty"].toString());
    content.append(" ");
    content.append(json["data"]["origin"]["author"].toString());
    content.append("\n\n");

    QJsonArray lines = json["data"]["origin"]["content"].toArray();
    for (int i = 0; i < lines.size(); i++)
    {
        content.append(lines[i].toString());
        content.append("\n");
    }

    //content.append(json["warning"].toString());

    ui->label->setText(content);

    reply->deleteLater();
}
